<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Rebecca\CustomGeneratorBundle\Manipulator;

use Sensio\Bundle\GeneratorBundle\Manipulator\Manipulator;

/**
 * Changes the PHP code of a YAML routing file.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class ServicesManipulator extends Manipulator {

    private $file;

    /**
     * Constructor.
     *
     * @param string $file The YAML routing file path
     */
    public function __construct($file) {
        $this->file = $file;
    }

    /**
     * Adds a routing resource at the top of the existing ones.
     *
     * @param string $bundle
     * @param string $format
     * @param string $prefix
     * @param string $path
     *
     * @return Boolean true if it worked, false otherwise
     *
     * @throws \RuntimeException If bundle is already imported
     */
    public function addService($bundle, $entity, $component) {
        /*  components.test:
          class: Rebecca\RebeccaBundle\Component\TestComponent
          arguments: ["RebeccaBundle:TiposNomina", "@doctrine.orm.entity_manager"]
         */
        $current = '';
        if (file_exists($this->file)) {
            $current = file_get_contents($this->file);

            // Don't add same bundle twice
            if (false !== strpos($current, $component)) {
                throw new \RuntimeException(sprintf('Component "%s" is already imported.', $component));
            }
        } elseif (!is_dir($dir = dirname($this->file))) {
            mkdir($dir, 0777, true);
        }

        $parts = explode('\\', $entity);
        $entityClass = array_pop($parts);
        $entityNamespace = implode('\\', $parts);

        $code = $current;
        $code .= "\n\n";
        $code .= "  components.$entityClass:\n";
        $code .= "    class: $component\n";
        $code .= "    arguments: [\"$bundle:$entityClass\", \"@doctrine.orm.entity_manager\"]\n";

        if (false === file_put_contents($this->file, $code)) {
            return false;
        }

        return true;
    }

}
